<?php

namespace StarCloud\Library;

use OSS\OssClient;

class AliyunOssClient
{
    const endpoint = 'https://oss-cn-beijing.aliyuncs.com';
    const accessKeyId = 'LTAI5t9UUC1GptPwG3M9ovCw';
    const accessKeySecret = 'HTKBkPSQKLwxVHxpvh9clmmc6DpPzk';
    const bucket = 'xinshidai-starclode';

    /**
     * Get an OSSClient instance according to config.
     *
     * @return OssClient An OssClient instance
     */
    public static function getOssClient(): OssClient
    {
        return new OssClient(self::accessKeyId, self::accessKeySecret, self::endpoint, false);
    }

    public static function getBucketName()
    {
        return self::bucket;
    }

    /**
     * A tool function which creates a bucket and exists the process if there are exceptions
     */
    public static function createBucket()
    {
        $ossClient = self::getOssClient();
        if (is_null($ossClient)) {
            exit(1);
        }
        $bucket = self::getBucketName();
        $acl = \OSS\OssClient::OSS_ACL_TYPE_PUBLIC_READ;
        try {
            $ossClient->createBucket($bucket, $acl);
        } catch (OssException $e) {
        }
    }

    public static function uploadOssBylocal($localFilePath = '')
    {
        try {
            $file_array = pathinfo($localFilePath);
            $basename = isset($file_array) ? $file_array['basename'] : '';
            $ossClient = new OssClient(self::accessKeyId, self::accessKeySecret, self::endpoint);
            $result = $ossClient->uploadFile(self::bucket, "star_cloud/{$basename}", $localFilePath);
        } catch (OssException $e) {
            printf(__FUNCTION__ . ": FAILED\n");
            printf($e->getMessage() . "\n");
            return response()->json(['link' => ""]);
        }
        @unlink($localFilePath);
        return $result['oss-request-url'];
    }
}
